package com.mi.rule.generator._0_0_0_yuan_zhuang;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
public class Generator {
    //TODO resource/templates 文件夹后缀
    private final static String templates = "_0_0_1";

    //TODO 代码包结构(根据项目动态修改)
    private final static String basePackage = "com.soul";//顶层包

    //TODO 生成规则
    //生成指定表  "test_table1,test_table2"
    private final static String createTables = "0_demo";
    //排除指定表  "test_table1,test_table2"
    private final static String excludeTables = null;

    //TODO 数据源
    private final static String ip = "127.0.0.1";
    private final static String port = "3306";
    private final static String databaseName = "nb_boot";
    private final static String driverName = "com.mysql.cj.jdbc.Driver";
    private final static String username = "root";
    private final static String password = "1234qwer";
    //    private final static String password = "123456";
    private final static String url = "jdbc:mysql://"
            + ip + ":" + port + "/" + databaseName + "?"
            + "serverTimezone=Asia/Shanghai&characterEncoding=UTF8&"
            + "zeroDateTimeBehavior=convertToNull&useUnicode=true&"
            + "useSSL=false&useTimezone=false";

    //TODO 模板文件生成位置
    private final static String projectPath = System.getProperty("user.dir");
    private final static String createPath = projectPath + "/generator/";


    private static AutoGenerator generator = null;


    public static void main(String[] args) {
        //清空文件
        delete(new File(createPath));

        //生成文件
        generator = new AutoGenerator();
        setGlobalConfig();//全局配置
        setDataSource();//数据源配置
        setStrategy();//策略配置
        setPackage();//包配置
        setCfg();//注入自定义配置，可以在 VM 中使用 cfg.abc 设置的值
        setTemplate();//模板配置
        generator.execute();
        System.out.println("文件生成完毕...................");

        //删掉垃圾文件
//        delete(new File(createPath + "/z_z_z_z"));
    }

    //全局配置
    private static void setGlobalConfig() {
        generator.setGlobalConfig(
                new GlobalConfig()
                        .setActiveRecord(true)
                        .setOutputDir(createPath)
//                        .setOpen(true)
                        .setOpen(false)
                        .setAuthor("王永吉")
                        .setFileOverride(false)
                        .setEnableCache(false)
                        .setBaseResultMap(false)
                        .setBaseColumnList(false)
                        .setKotlin(false)
                        .setMapperName("%sDao")
                .setEntityName("%s")
                .setXmlName("%sMapper")
                .setServiceName("I%sService")
                .setServiceImplName("%sServiceImpl")
                .setControllerName("%sRestController")
        );
    }

    //数据源配置
    private static void setDataSource() {
        generator.setDataSource(
                new DataSourceConfig()
                        .setDbType(DbType.MYSQL)
                        .setDriverName(driverName)
                        .setUrl(url)
                        .setUsername(username)
                        .setPassword(password)
                        // 自定义数据库表字段类型转换【可选】
                        .setTypeConvert(new MySqlTypeConvert() {
                            @Override
                            public DbColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
                                if (fieldType.toLowerCase().contains("bigint")) {
                                    return DbColumnType.STRING;
                                }
                                if (fieldType.toLowerCase().contains("varchar")) {
                                    return DbColumnType.STRING;
                                }
                                if (fieldType.toLowerCase().contains("char")) {
                                    return DbColumnType.STRING;
                                }
                                if (fieldType.toLowerCase().contains("longtext")) {
                                    return DbColumnType.STRING;
                                }
                                if (fieldType.toLowerCase().contains("tinyint")) {
                                    return DbColumnType.STRING;
                                }
                                if (fieldType.toLowerCase().contains("json")) {
                                    return DbColumnType.STRING;
                                }
                                if (fieldType.toLowerCase().contains("datetime")) {
                                    return DbColumnType.LOCAL_DATE_TIME;
                                }

                                return (DbColumnType) super.processTypeConvert(globalConfig, fieldType);
                            }
                        }));
    }

    //策略配置
    private static void setStrategy() {
        StrategyConfig strategyConfig = new StrategyConfig()
                .setTablePrefix(removeTablePrefix())
                .setFieldPrefix(removeFilePrefix())
                .setEntityBuilderModel(true)
                .setEntityColumnConstant(true)
                .setTableFillList(getTableFills())
                .setEntityTableFieldAnnotationEnable(true)
                .setRestControllerStyle(false)
                .setEntityLombokModel(true)
                .setNaming(NamingStrategy.underline_to_camel)
                .setColumnNaming(NamingStrategy.underline_to_camel);
        if (createTables != null) {
            strategyConfig.setInclude(createTables.split(","));
        }
        if (excludeTables != null) {
            strategyConfig.setExclude(excludeTables.split(","));
        }
//                        .setSuperMapperClass("com.big.mybatis.base.BaseMapper")

        // strategy.setCapitalMode(true)// 全局大写命名 ORACLE 注意
        //strategy.setSuperControllerClass("com.sample.model.common.BaseController") //指定 顶层 Controller
        //strategy.setSuperEntityClass("com.sample.model.common.BaseEntity") //指定 顶层 实体类
        //strategy.setSuperEntityColumns("id")  //抽出公用 字段
        //strategy.setControllerMappingHyphenStyle(true)    //驼峰 变为  "-"
        generator.setStrategy(strategyConfig);
    }

    //包配置
    private static void setPackage() {
        generator.setPackageInfo(
                new PackageConfig()
                        .setParent("z_z_z_z")
                        .setMapper("z_z_z_z")
                        .setEntity("z_z_z_z")
        );
    }

    //注入自定义配置，可以在 VM 中使用 cfg.abc 设置的值
    private static void setCfg() {
    }

    //模板配置
    private static void setTemplate() {
    }

    //去除表前缀
    private static String[] removeTablePrefix() {
        StringBuilder tablePrefix = new StringBuilder();
        tablePrefix.append("a_z_").append(",");
        tablePrefix.append("0_").append(",");
        tablePrefix.append("_").append(",");
        for (int i = 0; i < 26; i++) {
            tablePrefix.append((char) ('a' + i)).append("_").append(",");
        }
        return tablePrefix.toString().split(",");
    }

    //去除字段前缀
    private static String[] removeFilePrefix() {
        return "".split(",");
    }

    /**
     * 设置填充策略
     */
    protected static List<TableFill> getTableFills() {
        // 自定义需要填充的字段
        List<TableFill> tableFillList = new ArrayList<>();
        tableFillList.add(new TableFill("create_time", FieldFill.INSERT));
        tableFillList.add(new TableFill("update_time", FieldFill.INSERT_UPDATE));
        tableFillList.add(new TableFill("create_uid", FieldFill.INSERT));
        tableFillList.add(new TableFill("update_uid", FieldFill.INSERT_UPDATE));
        return tableFillList;
    }

    public static void delete(File file) {
        if (!file.exists()) return;
        if (file.isFile() || file.list() == null) {
            file.delete();
        } else {
            File[] files = file.listFiles();
            for (File a : files) {
                delete(a);
            }
            file.delete();
        }

    }
}



